#!/usr/bin/env python 
# -*- coding: utf-8 -*-

""" 
An echo server that uses select to handle multiple clients at a time. 
Entering any line of input at the terminal will exit the server. 
""" 

import select 
import socket
import time

host = '' 

import sys
try:
    port = int(sys.argv[1])
except:
    port = 50000

print "Server running on port %d" % port

backlog = 5 
size = 1024 
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((host,port)) 
server.listen(backlog) 
input = [server,sys.stdin] 
running = 1 

def sendCommand(client):
    #time.sleep(4)
    if port == 5000:
        client.send("File received: file:///filetesting.zip (TOI=1)\n") #1
        time.sleep(2)
        client.send("File received: file:///france.zip (TOI=1)\n") #1
    elif port == 5001:
        client.send("File received: file:///football.zip (TOI=1)\n") #2
        time.sleep(2)
        client.send("File received: file:///autre.zip (TOI=1)\n") #2

while running: 
    inputready,outputready,exceptready = select.select(input,[],[]) 

    for s in inputready: 

        if s == server: 
            # handle the server socket 
            client, address = server.accept() 
            input.append(client)
            sendCommand(client)

        elif s == sys.stdin: 
            # handle standard input 
            junk = sys.stdin.readline()
            running = 0
            
        else: 
            # handle all other sockets 
            data = s.recv(size)
            if data:
                for s2 in input:
                    if (s2 != server) and (s2 != sys.stdin): 
                        s2.send(data) 
            else: 
                s.close() 
                input.remove(s) 
                
                
server.close()